package org.jeecg.modules.filemanage.base.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.es.JeecgElasticsearchTemplate;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.filemanage.base.entity.FmCommentInfo;
import org.jeecg.modules.filemanage.base.entity.FmFileDetailsInfo;
import org.jeecg.modules.filemanage.base.mapper.FmCommentInfoMapper;
import org.jeecg.modules.filemanage.base.mapper.FmFileDetailsInfoMapper;
import org.jeecg.modules.filemanage.base.service.IFmCommentInfoService;
import org.jeecg.modules.filemanage.base.vo.commentView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: 评论表
 * @Author: jeecg-boot
 * @Date:   2021-04-20
 * @Version: V1.0
 */
@Service
public class FmCommentInfoServiceImpl extends ServiceImpl<FmCommentInfoMapper, FmCommentInfo> implements IFmCommentInfoService {
    @Autowired
    private FmCommentInfoMapper fmCommentInfoMapper;
    @Autowired
    private FmFileDetailsInfoServiceImpl fmFileDetailsInfoService;

    @Autowired
    private JeecgElasticsearchTemplate jeecgElasticsearchTemplate;

    public Page<FmCommentInfo> queryPagelikeList(Page<FmCommentInfo>pageList, String userid, String fileid){
        return pageList.setRecords(fmCommentInfoMapper.queryPagelikeList(pageList,  userid,  fileid));
    }

    public boolean add (FmCommentInfo fmCommentInfo){
        boolean res = false;
        res = super.save(fmCommentInfo);
        commentView cv = new commentView();
        if(fmCommentInfo.getId().isEmpty())
            cv.setId(UUIDGenerator.generate());
        else
            cv.setId(fmCommentInfo.getId());
        cv.setContent(fmCommentInfo.getContent());
        //通过文件id找文件fileid
        FmFileDetailsInfo fm = fmFileDetailsInfoService.getById(fmCommentInfo.getPid());
        if(fm!=null)
            cv.setFileid(fm.getFileid());
        saveOrUpdateEs(fmCommentInfo.getId(), JSONObject.parseObject(JSONObject.toJSONString(cv)), "filemanage");
        return res;
    }

    public boolean del (String id){
        boolean res = false;
        res = super.removeById(id);
        deleteEs(id,"filemanage");
        return res;
    }

    public boolean saveOrUpdateEs(String id, JSONObject data, String modelName){
        return  jeecgElasticsearchTemplate.save("comment_index",modelName,id,data);
    }

    private boolean deleteEs(String id,String modelName){
        return  jeecgElasticsearchTemplate.delete("comment_index",modelName,id);
    }
}
